package com.tcs.test.hive.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tcs.test.hive.IHiveApi;

public class HiveApi implements IHiveApi {

	private final Logger logger = LoggerFactory.getLogger(HiveApi.class);

	private static final String driverName = "org.apache.hive.jdbc.HiveDriver";
	
	StringBuilder sb = new StringBuilder();

	@Before
	@Override
	public void init() {
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			logger.error("", e);
		}
	}
	
	@Override
	public Connection getConnection(String url) throws SQLException {
		return DriverManager.getConnection("jdbc:hive2://slave1:10000/hive_demo1", "wangbo", "");
	}

	@Test
	public void test1() throws SQLException {
		// get connection
		Connection con = null;
		try {
			con = this.getConnection(null);
			// create statement
			Statement stmt = con.createStatement();
			// execute statement
//			sb.append("create database IF NOT EXISTS sogou");
//			execSql(stmt , sb.toString());
//			sb.setLength(0);
//			
//			sb.append("create external table if not exists sogou.sogou_20171112 (")
//					.append("time string,")
//					.append("tid string,")
//					.append("keywords string,")
//					.append("rank int,")
//					.append("ordering int,")
//					.append("url string )")
//					.append(" comment 'this is the sogou serach data of day'")
//					.append(" row format delimited")
//					.append(" fields terminated by '\t'")
//					.append(" STORED AS TEXTFILE")
//					.append(" location '/sogou/20171111'");
//			execSql(stmt, sb.toString());
			execSql(stmt, "use sogou");
			ResultSet resultSet = stmt.executeQuery("select count(1) from sogou_20171112");
			while (resultSet.next()) {
				logger.info(" 结果: {} " , resultSet.getString(1));
			}
		} catch (Exception e) {
			logger.error("" , e);
		} finally {
			con.close();
		}
	}
	
	private void execSql(Statement stmt,String sql) {
		try {
			stmt.execute(sql);
		} catch (SQLException e) {
			logger.error("" , e);
		}
		logger.info(" Table employee created.");
	}

}
